using System;
using System.Collections.Generic;
using System.Text;
using GetTogether.Studio.Schedule;

namespace GetTogether.Studio.Schedule
{
    public class ScheduleRunner
    {
        public static List<string> InvokingSchedules = new List<string>();
        public static void Run()
        {
            if (GetTogether.Studio.Config.Original.ScheduleStatus == 0) return;
            int sleepSeconds = GetTogether.Studio.Config.Original.ScheduleSleepSeconds;
            if (sleepSeconds <= 0) sleepSeconds = 30;
            sleepSeconds = sleepSeconds * 1000;
            new System.Threading.Thread(delegate()
            {
                while (true)
                {
                    string AppendParameter = "from-schedule=1";
                    ScheduleService ScheduleSvc = new ScheduleService();
                    Dictionary<string, string> InvokedResults = new Dictionary<string, string>();
                    try
                    {
                        List<string> ivScheduleNames = new List<string>();
                        foreach (string ivName in InvokingSchedules)
                        {
                            string[] ivNameInfo = ivName.Split(new string[] { " -> " }, StringSplitOptions.None);
                            if (ivNameInfo.Length > 0)
                                ivScheduleNames.Add(ivNameInfo[0]);
                        }
                        List<GetTogether.Studio.Schedule.ScheduleTask> schedules = ScheduleSvc.GetSchedules(ivScheduleNames);
                        if (schedules != null && schedules.Count > 0)
                        {
                            foreach (GetTogether.Studio.Schedule.ScheduleTask s in schedules)
                            {
                                new System.Threading.Thread(delegate()
                                {
                                    string scheduleInfo = string.Format("{0} -> Week:{1}, Time:{2}, Action On:{3}",
                                        s.Name,
                                        GetTogether.Utility.DateHelper.GetWeekdayString(s.Week),
                                        string.Concat(s.Date, (!string.IsNullOrEmpty(s.Date) ? " " : ""), s.Time, s.RepeatForTime ? "(Repeat)" : ""),
                                        DateTime.Now.ToString());
                                    try
                                    {
                                        StringBuilder sbLogs = new StringBuilder();
                                        string schName = s.Name;
                                        string error = string.Empty;
                                        string url = string.Empty;
                                        try
                                        {
                                            GetTogether.Net.Extension.WebClient wc = new GetTogether.Net.Extension.WebClient();
                                            wc.Timeout = int.MaxValue / 1000;
                                            wc.Encoding = System.Text.Encoding.UTF8;
                                            url = s.Url;
                                            url = string.Concat(url, ((url.IndexOf("?") < 0) ? "?" : "&"), AppendParameter);
                                            InvokingSchedules.Add(scheduleInfo);
                                            sbLogs.AppendLine(wc.DownloadString(url));
                                        }
                                        catch (Exception ex)
                                        {
                                            error = string.Concat(url, "\r\n", ex.ToString());
                                            sbLogs.AppendLine(error);
                                            GetTogether.Studio.Log.Error(ex, url);
                                        }
                                        ScheduleSvc.UpdateSchedule(schName, error, sbLogs.ToString());
                                    }
                                    catch (Exception ex)
                                    {
                                        GetTogether.Studio.Log.Error(ex, "");
                                    }
                                    finally
                                    {
                                        InvokingSchedules.Remove(scheduleInfo);
                                    }
                                }).Start();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        GetTogether.Studio.Log.Error(ex, "");
                    }
                    System.Threading.Thread.Sleep(sleepSeconds);
                }
            }).Start();
        }
    }
}
